<template>
  <div class="q-pa-md row" style="padding: 30px 80px">
    <div
      v-for="item in statusData"
      :key="item.key"
      class="col"
      style="padding: 0px 30px"
    >
      <q-card
        bordered
        class="sage-radius q-mb-sm q-mt-sm q-pa-md"
        style="min-height: 66%"
      >
        <div class="text-h6 text-blue-grey-9 text-bold text-center">
          {{ item.key }}
        </div>
        <q-separator class="q-mt-md q-mb-md" />
        <template v-if="item && item.value.length > 0">
          <div
            v-for="childItem in item.value"
            :key="childItem.key"
            class="q-mt-md q-pl-sm q-pr-sm"
          >
            <div
              class="row text-bold"
              style="font-size: 16px"
              @click="
                childItem.type === null || childItem.type === undefined
                  ? null
                  : typeClick(childItem)
              "
            >
              <span class="col text-grey-9">{{ childItem.key }}</span>
              <span
                :class="[
                  childItem.key === '设备状态'
                    ? statusColor[status.status]
                    : childItem.key === '底盘状态'
                    ? stm32Color[status.state]
                    : '',
                ]"
                >{{ childItem.value }}</span
              >
              <span v-if="childItem.operation" class="q-ml-sm"
                ><q-btn
                  :label="childItem.operation"
                  color="primary"
                  size="12px"
                  @click="itemClick(childItem)"
                ></q-btn
              ></span>
            </div>
          </div>
        </template>
        <template v-else>
          <h6 class="text-center">暂无库位信息</h6>
        </template>
      </q-card>
    </div>

    <modified-state ref="modifiedDialog" />

    <q-dialog v-model="visible">
      <q-card>
        <q-card-section class="text-h6">线边库复位</q-card-section>
        <q-separator />
        <div style="max-height: calc(100vh - 10rem); overflow: auto">
          <q-card-section class="q-gutter-sm q-pa-md">
            <q-input
              v-model="lineReset.targetPoseId"
              outlined
              label="工位点ID"
            />
            <q-input v-model="lineReset.spec" outlined label="规格" />
            <q-input
              v-model="lineReset.success"
              outlined
              label="放堵成功数量"
              type="number"
            />
          </q-card-section>
        </div>
        <q-slide-transition>
          <div v-show="incomplete" class="bg-primary">
            <q-btn
              unelevated
              class="full-width text-subtitle1 text-bold"
              color="primary"
              label="线边库复位"
              @click="reset"
            />
          </div>
        </q-slide-transition>
      </q-card>
    </q-dialog>
  </div>
</template>

<script>
import { computed, inject, ref, watch } from "vue";
import { api } from "boot/axios";
import { useAPIStore } from "stores/api";
import { useQuasar } from "quasar";
import ModifiedState from "components/amr/ModifiedState.vue";
import { status } from "src/utils/deviceWs";

const numberParam = [
  {
    label: "电量",
    value: "batteryNumber",
    unit: "%",
  },
  {
    label: "电压",
    value: "batteryVolt",
    unit: "V",
  },
  {
    label: "线速度",
    value: "linearSpeed",
    unit: "米/秒",
  },
  {
    label: "角速度",
    value: "angularSpeed",
    unit: "米/秒",
  },
  {
    label: "X坐标",
    value: "x",
  },
  {
    label: "Y坐标",
    value: "y",
  },
];

const statusColor = {
  idle: "text-secondary",
  running: "text-primary",
  pause: "text-bold text-warning",
  error: "text-bold text-negative",
};

const stm32Color = {
  PAUSE: "text-bold text-warning",
  NORMAL: "text-secondary",
  QUICKSTOP: "text-bold text-negative",
};

const statusName = {
  idle: "空闲",
  running: "运动中",
  pause: "暂停",
  error: "错误需复位",
};
const stm32State = {
  PAUSE: "暂停",
  NORMAL: "正常",
  QUICKSTOP: "急停",
};
export default {
  name: "AmrStatus",
  components: {
    ModifiedState,
  },
  setup() {
    const modifiedDialog = ref(null);
    const mapPoseName = ref("");
    const $q = useQuasar();
    const lineReset = ref({
      status: "UNLOAD_SUCCESS",
      targetPoseId: "",
      spec: "",
      count: 0,
    });
    const visible = ref(false);
    const incomplete = computed(() => lineReset.value.autoLine !== "");
    console.log("status", status);
    watch(
      () => status.value.mapPoseID,
      (newValue, oldValue) => {
        console.log("mapPoseID", newValue, oldValue);
        api.get(useAPIStore().amrUrl + "map/pose/id/" + newValue).then((rs) => {
          mapPoseName.value = rs.data.name || "没有获取到点位";
        });
      },
      {
        immediate: true,
      }
    );

    function itemClick(item) {
      console.log("item", item);
      switch (item.key) {
        case "末端高度": // 设定高度
          setHeight();
          break;
        case "线边库复位": // 线边库复位
          visible.value = true;
          break;
        case "机器人库位复位": // 机器人库位复位
          robotReset();
          break;
      }
    }

    function typeClick(item) {
      console.log("类型点击", item, modifiedDialog.value);
      modifiedDialog.value.show(item);
    }

    function setHeight() {
      $q.dialog({
        title: "调整末端升降机构",
        message: "将升降机构调节至目标高度？（单位 毫米）",
        prompt: {
          model: 0,
          type: "number",
        },
        cancel: true,
        persistent: true,
      }).onOk((data) => {
        api
          .post(useAPIStore().amrRosUrl + "call", [Number(data)], {
            params: { service: "stack_operate" },
          })
          .then((rs) => {
            switch (typeof rs.data.values) {
              case "string":
                $q.notify({
                  message: rs.data.values,
                  type: "negative",
                  position: "bottom",
                });
                break;
              case "object":
                if (rs.data.values.success) {
                  $q.notify({
                    message: "指令下发成功",
                    type: "positive",
                    position: "bottom",
                  });
                } else {
                  $q.notify({
                    message: rs.data.values.message,
                    type: "warning",
                    position: "bottom",
                  });
                }
            }
          });
      });
    }

    function robotReset() {
      console.log("222----机器人库位复位");
      $q.dialog({
        title: "机器人库位复位",
        message: "是否要复位",
        cancel: "取消",
        ok: "确认",
      }).onOk(() => {
        // api.post(useAPIStore().amrRosUrl + 'call', [], { params: { service: '/cargo_clear' } }).then(rs => { // TODO 修改
        api
          .post(
            useAPIStore().amrRosUrl + "call",
            {
              type: "Clear All",
              // id: 0,
              // used: 10
            },
            { params: { service: "/modify_local_storage" } }
          )
          .then((rs) => {
            if (rs.data.values.result === "success") {
              $q.notify({
                message: "纠正成功",
                type: "positive",
              });
            } else {
              $q.notify({
                message: "调用失败",
                type: "negative",
              });
            }
          })
          .catch(() => {
            $q.notify({
              message: "连接超时，请检查网络！",
              type: "negative",
            });
          });
      });
    }

    function reset() {
      console.log("---线边库复位");
      $q.dialog({
        title: "线边库复位",
        message: "是否要复位",
        cancel: "取消",
        ok: "确认",
      }).onOk(() => {
        api
          .get(useAPIStore().newTaskUrl + "amr", { params: lineReset.value })
          .then((rs) => {
            if (rs.data) {
              $q.notify({
                type: "positive",
                message: "线边库复位成功",
              });
              visible.value = false;
            } else {
              $q.notify({
                type: "negative",
                message: "操作失败",
              });
              visible.value = false;
            }
          });
      });
    }

    const statusData = computed(() => {
      const result = [
        {
          key: "基本信息",
          value: [
            {
              key: "设备ID",
              value: status.value.device,
              desc: "当前机器人ID",
            },
            {
              key: "设备类型",
              value: status.value.type,
              desc: "当前机器人类型",
            },
            {
              key: "设备IP",
              value: status.value.network && status.value.network.IPv4,
              desc: "当前机器人IP地址",
            },
            {
              key: "点位",
              value: mapPoseName.value,
              desc: "当前机械臂点位",
            },
            {
              key: "X坐标",
              value: status.value.x && status.value.x.toFixed(2),
              desc: "当前机械臂X坐标",
            },
            {
              key: "Y坐标",
              value: status.value.y && status.value.y.toFixed(2),
              desc: "当前机械臂Y坐标",
            },
          ],
        },
        {
          key: "状态信息",
          value: [
            {
              key: "设备状态",
              value: statusName[status.value.status] || status.value.status,
              desc: "机器人当前状态",
            },
            {
              key: "底盘状态",
              value: `${
                stm32State[status.value.state] || status.value.state || ""
              }`,
              desc: "机器人当前底盘状态",
            },
            {
              key: "线速度",
              value: `${(status.value.linearSpeed || 0).toFixed(2)}米/秒`,
              desc: "当前机械臂线速度",
            },
            {
              key: "角速度",
              value: `${(status.value.angularSpeed || 0).toFixed(2)}米/秒`,
              desc: "当前机械臂角速度",
            },
            {
              key: "阻挡时间",
              value: `${status.value.blockedTime || 0}`,
              desc: "阻挡时间",
            },
          ],
        },
        {
          key: "电源信息",
          value: [
            {
              key: "电量",
              value: `${(status.value.batteryNumber || 0).toFixed(2)}%`,
              desc: "机器人当前电量",
            },
            {
              key: "电压",
              value: `${(status.value.batteryVolt || 0).toFixed(2)}V`,
              desc: "机器人当前电压",
            },
            {
              key: "电流",
              value: `${(status.value.batteryCurrency || 0).toFixed(2)}A`,
              desc: "机器人当前电流",
            },
          ],
        },
        {
          key: "库位信息",
          value: [],
        },
      ];
      if (status.value.data && status.value.data.cargoList) {
        result[result.length - 1].value = status.value.data.cargoList
          .map((item) => {
            return {
              key: "类型：" + item.type,
              value: `${item.used}/${item.capacity}`,
              type: item.type,
              used: item.used,
              capacity: item.capacity,
              id: item.id,
            };
          })
          .concat([
            {
              key: "末端高度",
              value: `${
                (status.value.data && status.value.data.height) || 0
              }毫米`,
              operation: "设定高度",
              desc: "末端高度",
            },
            {
              key: "线边库复位",
              value: "",
              visibility: "hidden",
              operation: "复位",
              desc: "线边库复位",
            },
            {
              key: "机器人库位复位",
              value: "",
              visibility: "hidden",
              operation: "复位",
              desc: "机器人库位复位",
            },
          ]);
      }
      return result;
    });

    return {
      modifiedDialog,
      incomplete,
      visible,
      lineReset,
      statusData,
      numberParam,
      statusColor,
      stm32Color,
      statusName,
      status,
      reset,
      itemClick,
      typeClick,
      ModifiedState,
    };
  },
};
</script>

<style></style>
